package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {

    static String driver;
    static String url ;
    static String username ;
    static String password;

    protected Connection conn = null;
    protected PreparedStatement pstmt = null;
    protected ResultSet rs = null;

    static {
        init();
    }

    /**
     * 读取配置文件
     */
    public static void init(){
        try {
            // 创建一个properties对象
            Properties properties = new Properties();
            //  声明一个变量，他的值是 配置文件名
            String configFile = "database.properties";
            // 将配置文件读取到输入流中
            InputStream inStream = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
            // 从输入流中读取配置信息
            properties.load(inStream);

            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            // 加载jdbc驱动，要指定jdbc的驱动类 com.mysql.cj.jdbc.Driver
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     */
    public Connection getConnection(){
        Connection conn = null;
        // 建立连接，获取连接对象，要指定 连接字符串等
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public void closeAll(Connection conn, Statement stmt, ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            if (stmt!=null){
                stmt.close();
            }
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void closeAll(Connection conn, Statement stmt){
        try {
            if (rs!=null){
                rs.close();
            }
            if (stmt!=null){
                stmt.close();
            }
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
